﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Text;
using CardRegisterCollection.DBUtility;
using CardRegisterCollection.Model;

//Please add references
namespace CardRegisterCollection.DAL
{
    /// <summary>
    /// 数据访问类:user_role
    /// </summary>
    public partial class UserRole
    {
        public UserRole()
        { }
        #region  BasicMethod

        /// <summary>
        /// 得到最大ID
        /// </summary>
        public int GetMaxId()
        {
            return DbHelperOleDb.GetMaxID("ID", "user_role");
        }

        /// <summary>
        /// 是否存在该记录
        /// </summary>
        public bool Exists(string strWhere)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select count(1) from user_role");
            strSql.Append(" where DeleteFlag = 0 ");
            if (strWhere.Trim() != "")
            {
                strSql.Append(strWhere);
            }
            return DbHelperOleDb.Exists(strSql.ToString());
        }
        /// <summary>
        /// 查询是否存在用户绑定某个角色
        /// </summary>
        /// <param name="columnName"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public bool ColumnValueExists(string columnName, string value)
        {
            // 使用参数化查询防止 SQL 注入
            StringBuilder strSql = new StringBuilder();
            strSql.Append($"SELECT COUNT(1) FROM user_role WHERE {columnName} = @value");

            OleDbParameter[] parameters = {
                new OleDbParameter("@value", OleDbType.VarChar, 255)
            };
            parameters[0].Value = value;

            object result = DbHelperOleDb.GetSingle(strSql.ToString(), parameters);
            if (result != null && int.TryParse(result.ToString(), out int count))
            {
                return count > 0;
            }
            return false;
        }



        /// <summary>
        /// 获取UserRoleUnit集合
        /// </summary>
        /// <returns></returns>
        public List<Model.UserRoleUnit> GetListByUserId(string userId)
        {
            List<Model.UserRoleUnit> users = new List<Model.UserRoleUnit>();

            StringBuilder strSql = new StringBuilder();
            strSql.Append(" select UserId,RoleId,RoleName,UserName,TrueName,UnitId,DeptId,UnitName,DeptName from ((((");
            strSql.Append("(select UserId,RoleId from [user_role]) as ur ");
            strSql.Append("left join (select ID as uId,UserName,TrueName,UnitId,DeptId from [user]) as u on u.uId = ur.UserId)  ");
            strSql.Append("left join (select ID as u1Id,name as UnitName from [unit]) as u1 on u1.u1Id = u.UnitId)  ");
            strSql.Append("left join (select ID as d1Id,name as DeptName from [unit]) as d1 on d1.d1Id = u.DeptId)  ");
            strSql.Append("left join (select ID as r1Id,name as RoleName from [role]) as r1 on r1.r1Id = ur.RoleId) ");
            strSql.Append(" where  ur.UserId = @Id");

            OleDbParameter[] parameters = {
                new OleDbParameter("@Id",userId)
            };

            DataSet ds = DbHelperOleDb.Query(strSql.ToString(), parameters);
            if (ds.Tables[0].Rows.Count > 0)
            {
                users = DataTableToModel(ds.Tables[0]);
            }
            return users;
        }
        /// <summary>
        /// DataTable转换为Model类对象
        /// </summary>
        /// <param name="dt" DataTale></param>
        /// <returns></returns>
        private List<Model.UserRoleUnit> DataTableToModel(DataTable dt)
        {
            List<Model.UserRoleUnit> users = new List<Model.UserRoleUnit>();
            foreach (DataRow dr in dt.Rows)
            {
                Model.UserRoleUnit userRoleUnit = new Model.UserRoleUnit();
                userRoleUnit.UserId = dr["UserId"]?.ToString();
                userRoleUnit.RoleId = dr["RoleId"]?.ToString();
                userRoleUnit.RoleName = dr["RoleName"]?.ToString();
                userRoleUnit.UserName = dr["UserName"]?.ToString();
                userRoleUnit.TrueName = dr["TrueName"]?.ToString();
                userRoleUnit.UnitId = dr["UnitId"]?.ToString();
                userRoleUnit.DeptId = dr["DeptId"]?.ToString();
                userRoleUnit.UnitName = dr["UnitName"]?.ToString();
                userRoleUnit.DeptName = dr["DeptName"]?.ToString();
                users.Add(userRoleUnit);
            }
            return users;
        }

        /// <summary>
        /// 增加一条数据
        /// </summary>
        public bool Add(Model.UserRole model)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("insert into user_role(");
            strSql.Append("RoleId,UserId,CreatedBy,CreatedAt,ID)");
            strSql.Append(" values (");
            strSql.Append("@RoleId,@UserId,@CreatedBy,@CreatedAt,@ID)");
            OleDbParameter[] parameters = {
                    new OleDbParameter("@RoleId", OleDbType.VarChar,255),
                    new OleDbParameter("@UserId", OleDbType.VarChar,255),
                    new OleDbParameter("@CreatedBy", OleDbType.VarChar,255),
                    new OleDbParameter("@CreatedAt", OleDbType.Date),
                    new OleDbParameter("@ID", OleDbType.VarChar,255),
            };
            parameters[0].Value = model.RoleId;
            parameters[1].Value = model.UserId;
            parameters[2].Value = model.CreatedBy;
            parameters[3].Value = model.CreatedAt;
            parameters[4].Value = model.ID;

            int rows = DbHelperOleDb.ExecuteSql(strSql.ToString(), parameters);
            if (rows > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
      

        /// <summary>
        /// 删除一条数据
        /// </summary>
        public bool Delete(string userId)
        {

            StringBuilder strSql = new StringBuilder();
            strSql.Append("delete from user_role ");
            strSql.Append(" where UserId=@UserId");
            OleDbParameter[] parameters = {
                    new OleDbParameter("@UserId", OleDbType.VarChar,255)
            };
            parameters[0].Value = userId;

            int rows = DbHelperOleDb.ExecuteSql(strSql.ToString(), parameters);
            if (rows > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 批量删除数据
        /// </summary>
        public bool DeleteList(string IDlist)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("delete from user_role ");
            strSql.Append(" where ID in (" + IDlist + ")  ");
            int rows = DbHelperOleDb.ExecuteSql(strSql.ToString());
            if (rows > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }


        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public Model.UserRole GetModel(int ID)
        {

            StringBuilder strSql = new StringBuilder();
            strSql.Append("select ID,RoleId,UserId,CreatedBy,CreatedAt,DeleteFlag,LastUpdatedBy,LastUpdatedAt from user_role ");
            strSql.Append(" where ID=@ID");
            OleDbParameter[] parameters = {
                    new OleDbParameter("@ID", OleDbType.Integer,4)
            };
            parameters[0].Value = ID;

            Model.UserRole model = new Model.UserRole();
            DataSet ds = DbHelperOleDb.Query(strSql.ToString(), parameters);
            if (ds.Tables[0].Rows.Count > 0)
            {
                return DataRowToModel(ds.Tables[0].Rows[0]);
            }
            else
            {
                return null;
            }
        }


        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public Model.UserRole DataRowToModel(DataRow row)
        {
            Model.UserRole model = new Model.UserRole();
            if (row != null)
            {
                if (row["ID"] != null && row["ID"].ToString() != "")
                {
                    model.ID = row["ID"].ToString();
                }
                if (row["RoleId"] != null && row["RoleId"].ToString() != "")
                {
                    model.RoleId = row["RoleId"].ToString();
                }
                if (row["UserId"] != null && row["UserId"].ToString() != "")
                {
                    model.UserId = row["UserId"].ToString();
                }
                if (row["CreatedBy"] != null)
                {
                    model.CreatedBy = row["CreatedBy"].ToString();
                }
                if (row["CreatedAt"] != null && row["CreatedAt"].ToString() != "")
                {
                    model.CreatedAt = DateTime.Parse(row["CreatedAt"].ToString());
                }
                if (row["DeleteFlag"] != null && row["DeleteFlag"].ToString() != "")
                {
                    if ((row["DeleteFlag"].ToString() == "1") || (row["DeleteFlag"].ToString().ToLower() == "true"))
                    {
                        model.DeleteFlag = true;
                    }
                    else
                    {
                        model.DeleteFlag = false;
                    }
                }
                if (row["LastUpdatedBy"] != null)
                {
                    model.LastUpdatedBy = row["LastUpdatedBy"].ToString();
                }
                if (row["LastUpdatedAt"] != null && row["LastUpdatedAt"].ToString() != "")
                {
                    model.LastUpdatedAt = DateTime.Parse(row["LastUpdatedAt"].ToString());
                }
            }
            return model;
        }

        /// <summary>
        /// 获得数据列表
        /// </summary>
        public DataSet GetList(string strWhere)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select ID,RoleId,UserId,CreatedBy,CreatedAt,DeleteFlag,LastUpdatedBy,LastUpdatedAt ");
            strSql.Append(" FROM user_role ");
            if (strWhere.Trim() != "")
            {
                strSql.Append(" where " + strWhere);
            }
            return DbHelperOleDb.Query(strSql.ToString());
        }

        /// <summary>
        /// 获取记录总数
        /// </summary>
        public int GetRecordCount(string strWhere)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select count(1) FROM user_role ");
            if (strWhere.Trim() != "")
            {
                strSql.Append(" where " + strWhere);
            }
            object obj = DbHelperSQL.GetSingle(strSql.ToString());
            if (obj == null)
            {
                return 0;
            }
            else
            {
                return Convert.ToInt32(obj);
            }
        }
        /// <summary>
        /// 分页获取数据列表
        /// </summary>
        public DataSet GetListByPage(string strWhere, string orderby, int startIndex, int endIndex)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("SELECT * FROM ( ");
            strSql.Append(" SELECT ROW_NUMBER() OVER (");
            if (!string.IsNullOrEmpty(orderby.Trim()))
            {
                strSql.Append("order by T." + orderby);
            }
            else
            {
                strSql.Append("order by T.ID desc");
            }
            strSql.Append(")AS Row, T.*  from user_role T ");
            if (!string.IsNullOrEmpty(strWhere.Trim()))
            {
                strSql.Append(" WHERE " + strWhere);
            }
            strSql.Append(" ) TT");
            strSql.AppendFormat(" WHERE TT.Row between {0} and {1}", startIndex, endIndex);
            return DbHelperOleDb.Query(strSql.ToString());
        }

        /*
		/// <summary>
		/// 分页获取数据列表
		/// </summary>
		public DataSet GetList(int PageSize,int PageIndex,string strWhere)
		{
			OleDbParameter[] parameters = {
					new OleDbParameter("@tblName", OleDbType.VarChar, 255),
					new OleDbParameter("@fldName", OleDbType.VarChar, 255),
					new OleDbParameter("@PageSize", OleDbType.Integer),
					new OleDbParameter("@PageIndex", OleDbType.Integer),
					new OleDbParameter("@IsReCount", OleDbType.Boolean),
					new OleDbParameter("@OrderType", OleDbType.Boolean),
					new OleDbParameter("@strWhere", OleDbType.VarChar,1000),
					};
			parameters[0].Value = "user_role";
			parameters[1].Value = "ID";
			parameters[2].Value = PageSize;
			parameters[3].Value = PageIndex;
			parameters[4].Value = 0;
			parameters[5].Value = 0;
			parameters[6].Value = strWhere;	
			return DbHelperOleDb.RunProcedure("UP_GetRecordByPage",parameters,"ds");
		}*/

        #endregion  BasicMethod
        #region  ExtensionMethod

        #endregion  ExtensionMethod
    }
}

